<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>试题的录入</span>
      </div>
      <!-- 表单============================================== ======================================== ======================================== ======================================== -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        width="400px"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- 学科选择 -->
        <el-form-item label="学科人" prop="subjectID">
          <el-select
            class="widths"
            v-model="ruleForm.subjectID"
            placeholder="请选择"
            @change="remove"
          >
            <el-option
              v-for="(item, index) in subjectID"
              :key="index"
              :label="item.label"
              :value="item.value"
              @click.native="simpleSubjectFn(item.value)"
            >
              <span style="float: left">{{ item.label }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 目录选择 -->
        <el-form-item label="目录" prop="catalogID">
          <el-select
            class="widths"
            v-model="ruleForm.catalogID"
            placeholder="请选择"
          >
            <el-option
              v-for="item in catalogID"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            >
              <span style="float: left">{{ item.label }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 城市选择 -->
      <div class="chengshi">
        <el-form-item label="城市" prop="province">
          <el-select
            v-model="ruleForm.province"
            placeholder="请选择"
            @change="provinceChangeFn"
          >
            <el-option
              v-for="(item,index) in Myshi"
              :key="index"
              :label="item"
              :value="item"
            >
              <span style="float: left">{{ item }}</span>
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label-width="0" class="sd" prop="city">
           <el-select  v-model="ruleForm.city" placeholder="请选择">
            <el-option

              v-for="(item,index) in Myshi1"
              :key="index"
              :label="item"
              :value="item"
            >
              <span style="float: left">{{ item }}</span>
            </el-option>
          </el-select>
        </el-form-item></div>
        <!-- 企业选择 -->
        <el-form-item label="企业" prop="enterpriseID">
          <el-select
            class="widths"
            v-model="ruleForm.enterpriseID"
            placeholder="请选择"
          >
            <el-option
              v-for="item in enterprise"
              :key="item.id"
              :label="item.shortName"
              :value="item.id"
            >
              <span style="float: left">{{ item.shortName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 方向选择 -->
        <el-form-item label="方向" prop="direction">
          <el-select
            class="widths"
            v-model="ruleForm.direction"
            placeholder="请您选择"
          >
            <el-option
              v-for="item in direction"
              :key="item"
              :label="item"
              :value="item"
            >
              <span style="float: left">{{ item }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 提型选择 -->
        <el-form-item label="题型" prop="questionType">
          <el-radio-group v-model="ruleForm.questionType">
            <el-radio
              :label="String(itme.value)"
              v-for="itme in questionType1"
              :key="itme.value"
              @change="questionTypeFn"
            >
              {{ itme.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 难度 -->
        <el-form-item label="难度" prop="difficulty">
          <el-radio-group v-model="ruleForm.difficulty">
            <el-radio
              v-for="itme in difficulty"
              :key="itme.value"
              :label="String(itme.value)"

            >
              {{ itme.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 题干 -->
        <el-form-item class="chajian" label="题干" prop="question">
          <quill-editor
            v-model="ruleForm.question"
            ref="myQuillEditor"
            style="height: 170px"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @change="onEditorChange($event)"
          >
          </quill-editor>
        </el-form-item>

        <!-- 选项 -->

        <el-form-item v-if="!JaneReplied" label="选项">
          <div v-for="(itme, index) in xuanxiang" :ref="`index${index}`" :key="itme" class="group">
            <!-- 单选标签 -->
            <el-radio
              v-show="disabled === true"
              class="ss"
              :label="itme"
              v-model="options1.code"
              >{{ itme }}：</el-radio
            >
            <!-- title -->
            <el-checkbox
              v-show="disabled === false"
              v-model="options1.isRight[index]"
              >{{ itme }}：</el-checkbox
            >
            <!-- 多选标签 -->
            <el-input
              style="width: 200px"
              v-model="options1.title[index]"
            ></el-input>
            <!-- 上传照片组件 -->
           <div class="upimg">
              <upimg
              :staffPhotoUrl="options1.img[index]"
              @imgurl="imgURlFn"
              @upimgFn="upimgindex = index"

            />
          <span @click="chacha(index)" class="el-icon-circle-close cha"></span>
           </div>

          </div>

          <!-- 增加选项与答案按钮 -->
          <el-button @click="buttonFn" :disabled="disabled" type="danger"
            >+增加选项与答案</el-button>
            <el-button class="aa" @click="removeimg()" :disabled="disabled1" type="danger"  >-减少选项与答案</el-button>
        </el-form-item>

        <!-- 解析视频 -->
        <el-form-item label="解析视频">
          <el-input style="width: 300px" v-model="ruleForm.videoURL"></el-input>
        </el-form-item>
        <!-- 解析答案 -->
        <el-form-item class="chajian" label="解析答案" prop="answer">
          <quill-editor
            v-model="ruleForm.answer"
            ref="myQuillEditor"
            style="height: 170px"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @change="onEditorChange1($event)"
          >
          </quill-editor>
        </el-form-item>
        <!-- 题目备注 -->
        <el-form-item label="题目备注">
          <el-input
            style="width: 400px"
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="ruleForm.remarks"
          >
          </el-input>
        </el-form-item>
        <!-- 试题标签 -->
        <el-form-item label="试题标签" prop=" direction">
          <el-select
            class="widths"
            v-model="ruleForm.tags"
            multiple

    filterable
    allow-create
    default-first-option
            placeholder="请选择"
          >
            <el-option
              v-for="item in Label"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item>
          <el-button
            v-if="!ruleForm.id"
            type="primary"
            @click="submitForm('ruleForm')"
            >确认发布</el-button
          >
          <el-button v-else type="primary" @click="submitForm('ruleForm')"
            >确认修改</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor' // 调用编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// import map from '@/api/base/map.json'
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
import { simple } from '@/api/hmmm/subjects.js' // 学科目录请求
import { simple as simple1 } from '@/api/hmmm/directorys.js' // 目录请求
import { list } from '@/api/hmmm/companys.js' // 企业请求
import { simple as simple11 } from '@/api/hmmm/tags.js'
import { add, detail, update } from '@/api/hmmm/questions.js'

import upimg from '@/module-hmmm/components/up'
import { xuanxiangList } from '@/api/base'
import { provinces, citys } from '@/api/hmmm/citys.js'

export default {
  name: 'add',
  components: {
    quillEditor,
    upimg
  },

  data () {
    return {
      disabled1: false,
      i: 3, // 决定遍历几个选项
      upimgindex: 0,
      Myshi: [],
      Myshi1: [],
      options1: {
        // 选项
        img: [], // 图片地址
        isRight: [], // 是否正确答案
        code: [], // 代码
        title: [] // 标题
      },

      subjectID: '', // 学科列表
      catalogID: '', // 目录列表
      enterprise: '', // 企业列表
      direction: direction, // 方向列表
      questionType1: questionType,
      difficulty: difficulty,
      xuanxiang: [],
      disabled: true, // 按钮状态
      JaneReplied: false, // 简答状态
      Label: [], // 标签列表
      ruleForm: {
        id: '',
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        options: [], // 选项
        tags: [], // 标签
        // tags1: '',
        question: '', // 题干
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '' // 题目备注
      },
      rules: {
        subjectID: [
          { required: true, message: '请输入学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请至少选择一个方向', trigger: 'change' }
        ],

        desc: [{ required: true, message: '请填写活动形式', trigger: 'blur' }],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [
          { required: true, message: '请输入解析答案', trigger: 'blur' }
        ],
        remarks: [
          { required: true, message: '请输入解析答案', trigger: 'blur' }
        ]
      }
    }
  },
  async created () {
    if (this.i < 4) this.disabled1 = true
    this.ruleForm.id = this.$route.query.id
    if (this.ruleForm.id) {
      await this.TheDataIsFormatted() // 数据回填调用
      if (!this.disabled) this.i--
    }
    this.chengshi()
    this.gitdirectoryFn() // 调用简单学科
    this.getEnterpriseFn() // 调用企业目录

    this.buttonFn() // 调用增加按钮

    this.Myshi = provinces() // 城市
  },
  watch: {
    // 单选多选
    ruleForm: {
      handler (newName, oldName) {
        newName.questionType === '2'
          ? (this.disabled = false)
          : (this.disabled = true)

        newName.questionType === '3'
          ? (this.JaneReplied = true)
          : (this.JaneReplied = false)
        if (this.JaneReplied === true) {
          this.buttonFn()
          this.options1.title = []
        }
      },
      // 代表在wacth里声明了firstName这个方法之后立即先去执行handler方法
      deep: true,
      immediate: true
    },
    i () {
      console.log(this.i)
      this.i < 4 ? this.disabled1 = true : this.disabled1 = false
    }
  },
  methods: {
    onEditorReady (editor) {
      // 准备编辑器
    },
    onEditorBlur (a) {

    }, // 失去焦点事件
    onEditorFocus () {}, // 获得焦点事件
    // 内容改变事件
    onEditorChange (a) {
      this.ruleForm.question = a.html
    },
    // 内容改变事件
    onEditorChange1 (a) {
      this.ruleForm.answer = a.html
    },
    // 结算
    submitForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (!valid) return

        if (this.JaneReplied === false) {
          for (let ind = 0; ind < this.options1.title.length; ind++) {
          // 判断title没个输入框有没有值
            if (this.options1.title[ind] === null || this.options1.title[ind] === '') return this.$message('请填写答案选项！！！')
          // 判断单选时有没有勾选答案
          }
          if (this.disabled) {
            console.log('请填写正确答案！！！')
            if (this.options1.code === '' || this.options1.code.length === 0) return this.$message('请勾选正确答案！！！')
          } else {
          // 判断多选时有没有勾选答案
            const Judge = this.options1.isRight.every(itme => {
              return itme === false
            })
            console.log(this.disabled)
            if (Judge) return this.$message('至少勾选一个勾选正确答案！！！')
          }
        }
        this.geshihua() // 调用格式化发送请求的数据
        console.log(this.ruleForm)

        if (this.ruleForm.id) {
          this.ReviseQuestions() // 修改试题
          return
        }
        this.addQuestions() // 添加试题
      })
    },
    // 删除选项
    removeimg (a) {
      console.log(this.xuanxiang.length)

      this.i--

      this.xuanxiang.splice(this.xuanxiang.length - 1, 1)
      this.options1.title.splice(this.options1.title.length - 1, 1)
    },
    //   // 删除照片
    chacha (a) {
      this.options1.img.splice(a, 1)

      // console.log(this.$refs[`index${ind}`].parentNode().lastELementChild())
      // this.$refs[`index${ind}`].parentNode().lastELementChild().removeChild()

      // this.buttonFn(1)
    },
    // 完成后跳转页面并清除数据
    closaer () {
      this.options1 = {
        // 选项
        img: [], // 图片地址
        isRight: [], // 是否正确答案
        code: [], // 代码
        title: [] // 标题
      }
      this.ruleForm = {
        id: '',
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        options: [],
        tags: [],
        // tags1: '',
        question: '', // 题干
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '' // 题目备注
      }
      this.$router.push('list')
    },
    // 添加试题
    async addQuestions () {
      const res = await add(this.ruleForm)
      console.log(res)
      this.$message.success('添加成功')
      this.closaer()
    },
    // 修改试题

    async ReviseQuestions () {
      this.ruleForm.addDate = new Date()
      const res = await update(this.ruleForm)
      console.log(res)
      this.$message.success('更新成功')
      this.closaer()
    },
    // 数据回填格式化
    async TheDataIsFormatted () {
      this.options1.img = []
      const res = await detail(this.ruleForm)
      // 防止顺序被后台正乱了
      function compare (arg) {
        return function (a, b) {
          return a[arg] - b[arg]
        }
      }
      console.log(res.data.options.sort(compare('id')))
      res.data.options = res.data.options.sort(compare('id'))
      this.ruleForm = res.data
      console.log(this.i, res, '数据回填')

      // 字符串转成数组
      this.ruleForm.tags = res.data.tags.split(',')
      if (!res.data.options.length) this.$message('有脑残不给值就上传')
      // 根据后台返回的options数量遍历出几个选项

      this.i = (res.data.options.length - 1)
      console.log(res.data.options.length - 1, 'ss')
      // this.i--
      console.log(res.data.options.length)

      // 返回的数据做处理
      res.data.options.forEach((itme) => {
        this.options1.title.push(itme.title)
        this.options1.img.push(itme.img)
        this.options1.isRight.push(itme.isRight === 1)
      })
      console.log(this.options1.img, 'ajahskh')
      // 单选时
      if (this.disabled) {
        const app = res.data.options.find((itme) => {
          return itme.isRight === 1
        })

        // 正确答案返回到数据中
        this.options1.code = app.code
      }
      // 调用目录接口
      this.simpleSubjectFn(this.ruleForm.subjectID)

      // this.ruleForm.tags.push(res.data.tags)
    },
    // 子穿父返回照片地址
    imgURlFn (a) {
      this.options1.img[this.upimgindex] = a
    },
    // 增加选项按钮
    buttonFn () {
      if (!this.disabled) {
        this.i++
      }
      console.log(this.i, '层架')
      // 为多选时 每点一次➕1 决定了选项的数量
      xuanxiangList.forEach((itme) => {
        if (this.xuanxiang.length > this.i) return

        this.xuanxiang.push(xuanxiangList[this.xuanxiang.length])
        if (this.options1.title.length <= this.i) {
          this.options1.title.push(null)
        }
      })
      console.log(this.i)
    },

    editorOption () {},

    async gitdirectoryFn () {
      console.log('学科')
      const res = await simple()
      console.log(res, '学科')
      this.subjectID = res.data
    },
    remove () {
      this.ruleForm.catalogID = ''
    },
    // get简单目录
    async simpleSubjectFn (a) {
      const res = await simple1({ subjectID: a })
      console.log(res, 'get简单目录')
      this.catalogID = res.data
      const resp = await simple11({ subjectID: a })
      console.log(resp, 'resp')
      this.Label = resp.data
    },
    // 企业请求目录
    async getEnterpriseFn () {
      const res = await list()
      console.log(res, '企业请求目录')
      this.enterprise = res.data.items
    },
    // 目录值改变时
    subjectIDChangeFn () {},
    // 城市筛选市

    chengshi () {

      // this.Mykeys = Object.keys(map)
      // this.Myvalues = Object.values(map)

      // const b = RegExp('市')

      // this.Myshi = []

      // this.Mykeys.forEach((itmes) => {
      //   if (
      //     itmes.slice(3, 6) ===
      //       ('100' || '200' || '300' || '400' || '500' || '600' || '700') &&
      //     map[itmes].match(b)
      //   ) {
      //     this.Myshi.push({
      //       id: itmes,
      //       value: map[itmes]
      //     })
      //   }
      // })
    },
    // 区、县、地级市、县级市
    provinceChangeFn (a) {
      this.ruleForm.city = null
      this.Myshi1 = citys(a)
      // this.Myshi1 = []
      // const biaohao = this.Mykeys.filter((itme) => map[itme] === a)
      // this.Mykeys.forEach((itme) => {
      //   if (itme.slice(0, 4) === biaohao[biaohao.length - 1].slice(0, 4)) {
      //     this.Myshi1.push({
      //       id: itme,
      //       value: map[itme]
      //     })
      //   }
      // })
      // this.Myshi1.splice(0, 1)
    },
    questionTypeFn (a) {
      if (a === '多选') {
        this.options1.isRight = this.options1.isRight.map(itme => {
          return false
        })
      } else {
        this.options1.code = ''
      }
    },

    // 格式化
    geshihua () {
      const assss = []

      for (let index = 0; index < this.xuanxiang.length; index++) {
        console.log(xuanxiangList[index])
        if (this.disabled) {
          assss.push({
            title: this.options1.title[index] || '',
            code: this.xuanxiang[index],
            isRight: this.options1.code === xuanxiangList[index],
            img: this.options1.img[index]
          })
        } else {
          assss.push({
            title: this.options1.title[index] || '',
            code: this.xuanxiang[index],
            isRight: this.options1.isRight[index] === true,
            img: this.options1.img[index]
          })
        }
      }

      this.ruleForm.tags = this.ruleForm.tags.join()
      console.log(assss)
      this.$nextTick(() => {
        this.ruleForm.options = assss
      })
    }

  },
  computed: {
    editor () {
      return this.$refs.myQuillEditor.quill
    }
  }
}
</script>

<style >
.container {
  padding: 20px;
}
.upimg {
  display: inline-block;
  margin-left: 20px;

}
.group {
  display: flex;
  justify-items: center;

  line-height: 70px;
}
.froup {
  padding-top: 10px;
}
.ss {
  display: block;
  margin-left: 0;
  margin-right: 0;
  line-height: 70px;
}
.chajian {
  margin-bottom: 100px;
}
.widths {
  width: 400px;
}
 .cha{
       position: relative;
    top: -96px;
    left: 140px;
    font-size: 20px;
  }
  .chengshi{
    display: flex;
  }
  .sd{
    margin-left: 5px
  }
  .aa{
    margin-left: 10px;
  }
</style>
